#include "main_interface.h"
#include "ui_main_interface.h"

#include "global_variant.h"
#include "calculate_lowercomputer_data.h"
#include "dashboard_widget.h"
#include "dashboard_widget2.h"

#include <QKeyEvent>
#include <QDebug>

#include <QPropertyAnimation>

//大闸
int g_bigGateType = BigSmallGate::OperatingPositionType;

//小闸
int g_smallGateType = BigSmallGate::ReliefPositionType;
//总风缸压力
short g_totalWindCylinderPressure = 0;
//列车管压力
short g_trainPipePressure = 0;
//制动缸压力
short g_brakeCylinderPressure = 0;
//均衡风缸压力
short g_equalizeCylinderPressure = 0;


//大机速度值
short g_trainSpeedNum = 0;

//启动柴油发动机
bool g_startDieselEngine = false;


//前司机室挡位手柄位置（0，1，2，3，-1，-2，-3）
int g_throttleHandleFront  = 0;
//后司机室挡位手柄位置（0，1，2，3，-1，-2，-3）
int g_throttleHandleBehind  = 0;

//辅助制动
bool g_auxiliaryBraking = false;

//紧急制动
bool g_emergencyBraking = false;

//前司机室油门系数（-100到+100）
short g_throttleFactorFront = 0;

//后司机室油门系数（-100到+100）
short g_throttleFactorBehind = 0;

//电喇叭
bool g_electricHorn = false;

//风喇叭
bool g_windHorn = false;

MainInterface::MainInterface(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainInterface)
{
    ui->setupUi(this);

    //语音播报
    m_speech = new QTextToSpeech;
    m_speech->say("欢迎使用\"YZ-1G仪表硬件仿真系统\"软件"); //异步朗读文字

    //初始化界面
    initializeInterface();

    //初始化界面功能
    initializeFunction();
}

MainInterface::~MainInterface()
{
    //退出计算机下位机数据的线程
    m_calculateLowerComputerDataThread.quit();//停止事件循环
    m_calculateLowerComputerDataThread.wait();//阻塞知道线程结束

    delete ui;
}

//初始化界面
void MainInterface::initializeInterface()
{
    this->setWindowTitle("YZ-1G仪表硬件仿真系统软件v1.1.0.0");

    setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint);

    //keyboardshortcutLabel
    QPixmap icoPix;
    icoPix.load(":/Image/keyboardshortcut.png");
    icoPix.scaled(ui->keyboardshortcutLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->keyboardshortcutLabel->setScaledContents(true);
    ui->keyboardshortcutLabel->setPixmap(icoPix);

    //前司机室油门系数
    ui->gasPedalHorizontalSlider->setRange(-100, 100);
    connect(ui->gasPedalHorizontalSlider, &QSlider::valueChanged,
            this, [&](double value){
        g_throttleFactorFront = static_cast<short>(value);
    });

}

void MainInterface::initializeFunction()
{
    CalculateLowerComputerData* m_calculateLowerComputerData = new CalculateLowerComputerData;
    m_calculateLowerComputerData->moveToThread(&m_calculateLowerComputerDataThread);

    //是否开始计算下位机程序
    connect(this, &MainInterface::startCalculateLowerComputerData,
            m_calculateLowerComputerData, &CalculateLowerComputerData::startCalculateWork);

    connect(this, &MainInterface::stopCalculateLowerComputerData,
            m_calculateLowerComputerData, &CalculateLowerComputerData::stopCalculateWork);

    connect(&m_calculateLowerComputerDataThread, &QThread::finished,
            this, &CalculateLowerComputerData::deleteLater);

    connect( m_calculateLowerComputerData, &CalculateLowerComputerData::refreshShow,
            this, [&](){

                emit  sendTotalWindCylinderPressureAndbrakeCylinderPressureData(g_totalWindCylinderPressure, g_brakeCylinderPressure);

                emit sendTrainPipePressureDataAndEqualizeCylinderPressure(g_trainPipePressure, g_equalizeCylinderPressure);

                //总风缸、制动缸、列车管、均风缸
                ui->totalWindCylinderPressureLabel->setText( QString::number(g_totalWindCylinderPressure, 10));

                ui->brakeCylinderPressureLabel->setText(QString::number(g_brakeCylinderPressure, 10));

                ui->trainPipePressureLabel->setText(QString::number(g_trainPipePressure, 10));

                ui->equalizeCylinderPressureLabel->setText(QString::number(g_equalizeCylinderPressure, 10));


                ui->gasPedalLabel->setText(QString("前司机室油门系数：") + QString::number(g_throttleFactorFront, 10));
                //大小闸显示
                switch(g_bigGateType){//连挂：大运小缓；单个车：大缓小缓
                case BigSmallGate::RetarderLocationType :
                    ui->bigGateLabel->setText("制动位");

                    emit sendBigGatePressDown(false);
                    emit sendBigGateValueChanage(-25);
                    break; // 可选的
                case BigSmallGate::PreservationPressureLocationType :
                    ui->bigGateLabel->setText("保压位");

                     emit sendBigGatePressDown(false);
                    emit sendBigGateValueChanage(10);
                    break; // 可选的
                case BigSmallGate::OperatingPositionType:
                    ui->bigGateLabel->setText("运转位");

                     emit sendBigGatePressDown(false);
                    emit sendBigGateValueChanage(40);
                    break;
                case BigSmallGate::ReliefPositionType:
                    ui->bigGateLabel->setText("缓解位");

                     emit sendBigGatePressDown(false);
                     emit sendBigGateValueChanage(70);

                    break;
                case BigSmallGate::PressDownType:
                    ui->bigGateLabel->setText("下压位");

                    emit sendBigGatePressDown(true);
                    break;
                default : // 可选的
                    break;
                }

                switch(g_smallGateType){//连挂：大运小缓；单个车：大缓小缓
                case BigSmallGate::RetarderLocationType :
                    ui->smallGateLabel->setText("制动位");

                    emit sendSmallGatePressDown(false);
                    emit sendSmallGateValueChanage(-25);
                    break; // 可选的
                case BigSmallGate::PreservationPressureLocationType :
                    ui->smallGateLabel->setText("保压位");

                    emit sendSmallGatePressDown(false);
                    emit sendSmallGateValueChanage(10);
                    break; // 可选的
                case BigSmallGate::OperatingPositionType:
                    ui->smallGateLabel->setText("运转位");

                    emit sendSmallGatePressDown(false);
                    emit sendSmallGateValueChanage(40);
                    break;
                case BigSmallGate::ReliefPositionType:
                    ui->smallGateLabel->setText("缓解位");

                    emit sendSmallGatePressDown(false);
                    emit sendSmallGateValueChanage(70);
                    break;
                case BigSmallGate::PressDownType:
                    ui->smallGateLabel->setText("下压位");

                     emit sendSmallGatePressDown(true);
                    break;
                default : // 可选的
                    break;
                }

                if(g_emergencyBraking){
                    ui->emergencyBrakingLabel->setText("开");
                }else{
                    ui->emergencyBrakingLabel->setText("关");
                }

                if(g_auxiliaryBraking){
                    ui->auxiliaryBrakingLabel->setText("开");
                }else{
                    ui->auxiliaryBrakingLabel->setText("关");
                }

                if(g_startDieselEngine){
                    ui->startDieselEngineLabel->setText("开");
                }else{
                    ui->startDieselEngineLabel->setText("关");
                }

            });

    //设置线程优先级
    /*
    QThread::InheritPriority (给创建的线程赋予目前线程同样的等级（默认情况下就为这个）) ,
    QThread::TimeCriticalPriority (尽可能频繁的调度),
     QThread::HighestPriority  >  QThread::HighPriority >  QThread::NormalPriority(操作系统默认的优先级)
    > QThread::LowPriority > QThread::LowestPriority  >QThread::IdlePriority (没有其他线程运行的时候才进行调度)
      */
    // m_calculateLowerComputerDataThread.setPriority(QThread::InheritPriority);
    m_calculateLowerComputerDataThread.start();

    emit startCalculateLowerComputerData();

    //总风缸、制动缸
    DashBoardWidget *dashBoardWidget = new DashBoardWidget(this);
    dashBoardWidget->setUnit("kPa");
    dashBoardWidget->setText("压力值");
    dashBoardWidget->setmax(1200);
    // dashBoardWidget->move(600, 20);
    dashBoardWidget->setGeometry(20, 20, 300, 300);

    //发送总风、制动压力
    connect(this, &MainInterface::sendTotalWindCylinderPressureAndbrakeCylinderPressureData,
            dashBoardWidget, &DashBoardWidget::valueChanged);


    //列车管、均风缸
    DashBoardWidget *dashBoardWidget2 = new DashBoardWidget(this);
    dashBoardWidget2->setUnit("kPa");
    dashBoardWidget2->setText("压力值");
    dashBoardWidget2->setmax(1200);
    // dashBoardWidget->move(600, 20);
    dashBoardWidget2->setGeometry(20, 300, 300, 300);

    //发送总风、制动压力
    connect(this, &MainInterface::sendTrainPipePressureDataAndEqualizeCylinderPressure,
            dashBoardWidget2, &DashBoardWidget::valueChanged);

    //大闸
    DashBoardWidget2 *dashBoardWidget3 = new DashBoardWidget2(this);
    dashBoardWidget3->setMeterImagePath(":/Image/bigGate.png");
    dashBoardWidget3->setGeometry(400, 20, 500, 500);

    //手柄转动
    connect(this, &MainInterface::sendBigGateValueChanage,
            dashBoardWidget3, &DashBoardWidget2::valueChanged);

    //闸下压
    connect(this, &MainInterface::sendBigGatePressDown,
            dashBoardWidget3, &DashBoardWidget2::gatePressDownStatusChanged);


    //小闸
    DashBoardWidget2 *dashBoardWidget4 = new DashBoardWidget2(this);
     dashBoardWidget4->setMeterImagePath(":/Image/smallGate.png");
    dashBoardWidget4->setGeometry(400, 340, 500, 500);

    //手柄转动
     connect(this, &MainInterface::sendSmallGateValueChanage,
             dashBoardWidget4, &DashBoardWidget2::valueChanged);

    //闸下压
    connect(this, &MainInterface::sendSmallGatePressDown,
            dashBoardWidget4, &DashBoardWidget2::gatePressDownStatusChanged);


}

QImage MainInterface::rotateImage(const QImage &image, qreal fAngle)
{
    QTransform transform;
    transform.rotate(fAngle);

    return image.transformed(transform, Qt::SmoothTransformation);
}

void MainInterface::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Q) {//大闸 缓解位
        qDebug()<<"Q";

        // this->releaseKeyboard();   // 释放捕获的键盘输入


        g_bigGateType = BigSmallGate::ReliefPositionType;

    }else if(event->key() == Qt::Key_W){//大闸 运转位
        qDebug()<<"W";

        g_bigGateType = BigSmallGate::OperatingPositionType;

    }else if(event->key() == Qt::Key_E){//大闸 保压位
        qDebug()<<"E";

        g_bigGateType = BigSmallGate::PreservationPressureLocationType;
    }else if(event->key() == Qt::Key_R){//大闸 制动位
        qDebug()<<"R";

        g_bigGateType =  BigSmallGate::RetarderLocationType;
    }else if(event->key() == Qt::Key_T){//大闸 下压
        qDebug()<<"R";
        m_bigGateTypeEver = g_bigGateType;

        g_bigGateType =  BigSmallGate::PressDownType;
    }

    if(event->key() == Qt::Key_A) {//小闸 缓解位
        qDebug()<<"A";
        // this->releaseKeyboard();   // 释放捕获的键盘输入

        g_smallGateType =  BigSmallGate::ReliefPositionType;
    }else if(event->key() == Qt::Key_S){//小闸 运转位
        qDebug()<<"S";

        g_smallGateType = BigSmallGate::OperatingPositionType;
    }else if(event->key() == Qt::Key_D){//小闸 保压位
        qDebug()<<"D";

        g_smallGateType = BigSmallGate::PreservationPressureLocationType;
    }else if(event->key() == Qt::Key_F){//小闸 制动位
        qDebug()<<"F";

        g_smallGateType = BigSmallGate::RetarderLocationType;


    }else if(event->key() == Qt::Key_G){//小闸 下压
        qDebug()<<"G";
        m_smallGateTypeEver = g_smallGateType;

        g_smallGateType =  BigSmallGate::PressDownType;
    }

    else if(event->key() == Qt::Key_Y){//紧急制动
        qDebug()<<"Y";

        if(g_emergencyBraking == false){//紧急制动优先
            g_auxiliaryBraking = false;
        }
        g_emergencyBraking = (g_emergencyBraking == true) ? false: true;

    }

    else if(event->key() == Qt::Key_U){//辅助制动
        qDebug()<<"U";
        if(g_emergencyBraking == false){
            g_auxiliaryBraking = (g_auxiliaryBraking == true) ? false: true;
        }
    }

    if(event->key() == Qt::Key_Z){//开启/关闭柴油发动机
        qDebug()<<"Z";

        g_startDieselEngine = (g_startDieselEngine == true)? false: true;
    }

    if(event->key() == Qt::Key_X){//前司机室油门系数减少
        qDebug()<<"X";

        if(g_throttleFactorFront - 1 >= (-100)){
           g_throttleFactorFront -= 1;
        }

        ui->gasPedalHorizontalSlider->setValue(g_throttleFactorFront);
    }
    else if(event->key() == Qt::Key_C){//前司机室油门系数加
        qDebug()<<"C";

        if(g_throttleFactorFront + 1 <= 100){
            g_throttleFactorFront += 1;
        }

        ui->gasPedalHorizontalSlider->setValue(g_throttleFactorFront);
    }

    if(event->key() == Qt::Key_V){//前司机室挡位加
        qDebug()<<"X";
        if(g_throttleHandleFront - 1 >= -3){
            g_throttleHandleFront -= 1;
        }

        ui->throttleHandleLabel->setText(QString::number(g_throttleHandleFront, 10));
    }
    else if(event->key() == Qt::Key_B){//前司机室挡位减
        qDebug()<<"C";

        if(g_throttleHandleFront + 1 <= 3){
            g_throttleHandleFront += 1;
        }

        ui->throttleHandleLabel->setText(QString::number(g_throttleHandleFront, 10));
    }

    else if(event->key() == Qt::Key_N){//电喇叭
        qDebug()<<"N";
        g_electricHorn = true;

        ui->electricHornLabel->setText("开");

    }
    else if(event->key() == Qt::Key_M){//风喇叭
        qDebug()<<"M";

        g_windHorn = true;

        ui->windHornLabel->setText("开");
    }

}

void MainInterface::keyReleaseEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_T){//大闸 下压
        qDebug()<<"R";

        g_bigGateType =  m_bigGateTypeEver;
    }

    if(event->key() == Qt::Key_G){//小闸 下压
        qDebug()<<"G";

        g_smallGateType =  m_smallGateTypeEver;
    }

    else if(event->key() == Qt::Key_N){//电喇叭
        qDebug()<<"N";

        g_electricHorn = false;

        ui->electricHornLabel->setText("关");
    }
    else if(event->key() == Qt::Key_M){//风喇叭
        qDebug()<<"M";

        g_windHorn = false;

        ui->windHornLabel->setText("关");
    }
}
